package com.activemanager.workoutAssistant;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.activemanager.dashboard.H0Activity;
import com.activemanager.myHealthProfile.Q1MainActivity;
import com.example.android.navigationdrawerexample.R;
import com.example.android.navigationdrawerexample.R.drawable;
import com.example.android.navigationdrawerexample.R.id;
import com.example.android.navigationdrawerexample.R.layout;
import com.example.qiehuanactivity.QiehuanActivity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class WorkoutAssistant_W3 extends Activity {
	ImageView image = null;
	ImageButton iBWorkoutW1_start = null;
	ImageButton iBWorkoutW1_stop = null;
	TextView TVWorkoutW1_count = null;
	MyHandler myHandler = null;
	TimeThread timeThread = null;
	boolean isfinish = true;
	int hours, mins, seconds;
	int minseconds;
	TextView W3_textView_minsecond;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.workout_assistant_w3);
		// View rootView = inflater.inflate(R.layout.workout_assistant_w1,
		// container, false);
		image = (ImageView) findViewById(R.id.imageView3);
		iBWorkoutW1_start = (ImageButton) findViewById(R.id.iBWorkoutW1_start);
		iBWorkoutW1_stop = (ImageButton) findViewById(R.id.iBWorkoutW1_stop);
		iBWorkoutW1_stop.setVisibility(View.GONE);
		TVWorkoutW1_count = (TextView) findViewById(R.id.TVWorkoutW1_count);
		W3_textView_minsecond = (TextView)findViewById(R.id.W3_textView_minsecond);
		myHandler = new MyHandler();
		hours = 0;
		mins = 0;
		seconds = 0;
		minseconds = 0;
		isfinish = true;
		
		
		ImageView img_home = (ImageView) findViewById(R.id.imageView);
		img_home.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}});

		initPic();
		image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(WorkoutAssistant_W3.this,
						QiehuanActivity.class);
				startActivity(intent);
			}
		});
		iBWorkoutW1_start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isfinish) {
if(hours == 0 && mins == 0 && seconds==0 && minseconds == 0) {
						startDialog();
					} else {
					isfinish = false;
					if (timeThread == null || !timeThread.isAlive()) {
						timeThread = new TimeThread();
						timeThread.start();
					}
					iBWorkoutW1_stop.setVisibility(View.GONE);
					iBWorkoutW1_start
							.setBackgroundResource(R.drawable.button_pause_style);
					}} else if(!isfinish){
					isfinish = true;
					iBWorkoutW1_start
							.setBackgroundResource(R.drawable.button_stopstart_style);
					iBWorkoutW1_stop.setVisibility(View.VISIBLE);
					iBWorkoutW1_stop.setBackgroundResource(R.drawable.button_stopstop_style);
				}
			}
		});
		
		iBWorkoutW1_stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				iBWorkoutW1_start
				.setBackgroundResource(R.drawable.button_start_style);
				iBWorkoutW1_stop.setVisibility(View.GONE);
				hours = 0;
				mins = 0;
				seconds = 0;
				minseconds = 0;
				DecimalFormat decimalFormat = new DecimalFormat("00");
					TVWorkoutW1_count.setText(hours + ":"
						+ decimalFormat.format(mins) + ":"
						+ decimalFormat.format(seconds));
				W3_textView_minsecond.setText(decimalFormat.format(minseconds));
				Intent intent = new Intent();
				intent.setClass(WorkoutAssistant_W3.this, QiehuanActivity.class);
				startActivity(intent);
			}
		});
		
		Button btn_history = (Button) findViewById(R.id.btn_history);
		btn_history.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(WorkoutAssistant_W3.this,
							WorkoutHistory_C1.class);
				startActivity(intent);
			}
			});
		
		
		ImageButton btn_img = (ImageButton) findViewById(R.id.IBtnSelectSport);
		btn_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final BitmapFactory.Options opt = new BitmapFactory.Options();
				opt.inPreferredConfig = Bitmap.Config.RGB_565;
				opt.inPurgeable = true;
				opt.inInputShareable = true;

				final Dialog dialog = new Dialog(WorkoutAssistant_W3.this,
						R.style.MyDialog);
				dialog.setContentView(R.layout.p13);
				final RelativeLayout bg_img = (RelativeLayout) dialog
						.findViewById(R.id.linearLayout);
//				InputStream bg_is = getResources().openRawResource(R.drawable.u165_normal);
//				Bitmap bg_bit = BitmapFactory.decodeStream(bg_is, null, opt);
//				bg_img.setBackgroundDrawable(new BitmapDrawable(bg_bit));
				bg_img.setBackgroundResource(R.drawable.bg_for_popup_54);
				
				ImageView img = (ImageView) dialog
						.findViewById(R.id.imageView1);
				Button btn1 = (Button) dialog.findViewById(R.id.button1);
				Button btn2 = (Button) dialog.findViewById(R.id.button2);
				TextView tv = (TextView) dialog.findViewById(R.id.textView1);
				InputStream is = getResources().openRawResource(
						R.drawable.d_warning);
				Bitmap bit = BitmapFactory.decodeStream(is, null, opt);
				img.setImageBitmap(bit);

				tv.setText("Are you sure to stop current\n    workout recording");
				btn1.setText("Cancel");
				btn2.setText("Yes");

				btn1.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						dialog.dismiss();
					}
				});

				btn2.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						isfinish = true;
						iBWorkoutW1_start
							.setBackgroundResource(R.drawable.button_stopstart_style);
						iBWorkoutW1_stop.setVisibility(View.VISIBLE);
						iBWorkoutW1_stop.setBackgroundResource(R.drawable.button_stopstop_style);
						chooseSports(dialog);

					}

				});

				Window dialogWindow = dialog.getWindow();
				WindowManager m = getWindowManager();
				Display d = m.getDefaultDisplay();
				WindowManager.LayoutParams p = dialogWindow.getAttributes();
				p.height = (int) (d.getHeight() * 0.47);
				p.width = (int) (d.getWidth() * 0.95);
				dialogWindow.setAttributes(p);
				if (!isfinish)
					dialog.show();
				else
					chooseSports(dialog);

				//

				Button btnDialog_Ok = (Button) dialog
						.findViewById(R.id.button1);
				btnDialog_Ok.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						dialog.dismiss();
					}
				});
			}
		});

	}
	
	private void chooseSports(final Dialog dialog) {
		// TODO Auto-generated method stub
		final BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;

		dialog.setContentView(R.layout.p30);
		final LinearLayout img = (LinearLayout) dialog
				.findViewById(R.id.linearLayout);
		InputStream is = getResources().openRawResource(R.drawable.u165_normal);
		Bitmap bit = BitmapFactory.decodeStream(is, null, opt);
		img.setBackgroundDrawable(new BitmapDrawable(bit));

		dialog.show();
		Window dialogWindow = dialog.getWindow();
		WindowManager m = getWindowManager();
		Display d = m.getDefaultDisplay();
		WindowManager.LayoutParams p = dialogWindow.getAttributes();
		p.height = (int) (d.getHeight() * 0.765);
		p.width = (int) (d.getWidth() * 0.95);
		dialogWindow.setAttributes(p);

		String[] mFrom = new String[] { "profile_img", "profile_item" };
		String[] profileTitle = { "Jogging", "Badminton", "Badminton PRO",
				"Cycling", "Walking", "Dance" };
		int[] mTo = new int[] { R.id.profile_img, R.id.profile_item };
		List<Map<String, Object>> mList = new ArrayList<Map<String, Object>>();
		Map<String, Object> mMap = null;
		for (int i = 0; i < profileTitle.length; i++) {
			mMap = new HashMap<String, Object>();
			int drawable = getResources().getIdentifier(
					"choose_u" + (155 + i) + "_normal", "drawable",
					WorkoutAssistant_W3.this.getPackageName());
			mMap.put("profile_img", drawable);
			mMap.put("profile_item", profileTitle[i]);
			mList.add(mMap);
		}
		final ListView mListView = (ListView) dialog
				.findViewById(R.id.list_view);
		SimpleAdapter mAdapter = new SimpleAdapter(WorkoutAssistant_W3.this,
				mList, R.layout.drawer_list_item_for_sports, mFrom, mTo);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				if (pos == 0) {
					isfinish = true;
					intent.setClass(WorkoutAssistant_W3.this,
							WorkoutAssistant_W1.class);
					startActivity(intent);
					dialog.dismiss();
					finish();
				} else if (pos == 1) {
					isfinish = true;
					intent.setClass(WorkoutAssistant_W3.this,
							WorkoutAssistant_W2.class);
					startActivity(intent);
					dialog.dismiss();
					finish();
				}
			}
		});

		Button btn_cancel = (Button) dialog.findViewById(R.id.button1);
		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
	}

	private void initPic() {
		// TODO Auto-generated method stub
		
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		
		RelativeLayout bgLayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
//		InputStream is = getResources().openRawResource(
//				R.drawable.background_normal);
//		Bitmap bgbit = BitmapFactory.decodeStream(is, null, opt);
//		bgLayout.setBackgroundDrawable(new BitmapDrawable(bgbit));
		bgLayout.setBackgroundResource(R.drawable.bg_540);
		
		ImageButton btn_img = (ImageButton) findViewById(R.id.IBtnSelectSport);
		InputStream is1 = getResources().openRawResource(
				R.drawable.u21_normal_w);
		Bitmap bgbit1 = BitmapFactory.decodeStream(is1, null, opt);
		btn_img.setBackgroundDrawable(new BitmapDrawable(bgbit1));
	}

	private class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			
			// System.out.println(msg.what+"");
			DecimalFormat decimalFormat = new DecimalFormat("00");
			if (msg.what == 1 && !isfinish) {
				minseconds++;
				if(minseconds == 100) {
					minseconds = 0;
					seconds++;
				}
				if (seconds == 60) {
					seconds = 0;
					mins++;
				}
				if (mins == 60) {
					mins = 0;
					hours++;
				}
			
				TVWorkoutW1_count.setText(hours + ":"
						+ decimalFormat.format(mins) + ":"
						+ decimalFormat.format(seconds));
				W3_textView_minsecond.setText(decimalFormat.format(minseconds));
			}
		}
	}

	
	class TimeThread extends Thread {

		@Override
		public void run() {
			while (!isfinish) {
				try {
					sleep(10);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message sendMsg = myHandler.obtainMessage();
				sendMsg.what = 1;
				myHandler.sendMessage(sendMsg);
			}
		}
	}
	
	public void startDialog() {
		final BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		final Dialog dialog = new Dialog(WorkoutAssistant_W3.this,
				R.style.MyDialog);

		dialog.setContentView(R.layout.p18_for_workout);

		final ImageView img = (ImageView) dialog.findViewById(R.id.imageView1);
		final LinearLayout bg = (LinearLayout) dialog
				.findViewById(R.id.dLinearLayout);
		final TextView tv = (TextView) dialog.findViewById(R.id.textView2);
		final TextView tv_long = (TextView) dialog.findViewById(R.id.textView3);
		InputStream is = getResources().openRawResource(R.drawable.u218_normal);
		Bitmap bit = BitmapFactory.decodeStream(is, null, opt);
		img.setBackgroundDrawable(new BitmapDrawable(bit));

		InputStream is1 = getResources()
				.openRawResource(R.drawable.u165_normal);
		Bitmap bit1 = BitmapFactory.decodeStream(is1, null, opt);
		bg.setBackgroundDrawable(new BitmapDrawable(bit1));

		tv.setTextSize(20);
		tv.setText("CALIBRATE��YOUR GEARS");
		tv_long.setText("             Calibration is finished\n now put your phone at a sage place\nmake sure your phone is in 3 meters\n            from the court boundary");
		createDialog(dialog);

		final Button ok = (Button) dialog.findViewById(R.id.btn_ok);
		ok.setText("Start");
		ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				tv.setText("CALIBRATING");
				tv_long.setText("Keep this posture stable until\n      calibration is done.");
				bg.removeView(ok);
				// ok.setVisibility(View.INVISIBLE);
				final LinearLayout layout2 = new LinearLayout(
						WorkoutAssistant_W3.this);
				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					     LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

				layoutParams.setMargins(0, 20, 0, 0);
				layout2.setGravity(Gravity.CENTER_HORIZONTAL);
				layout2.setOrientation(LinearLayout.HORIZONTAL);
				layout2.setLayoutParams(layoutParams);
				final ImageView btn1 = new ImageView(WorkoutAssistant_W3.this);
				final ImageView btn2 = new ImageView(WorkoutAssistant_W3.this);
				final ImageView btn3 = new ImageView(WorkoutAssistant_W3.this);
				Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.p3lhand);
				btn1.setImageDrawable(new BitmapDrawable(bitmap));
				Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(),
						R.drawable.p3lfoot);
				btn2.setImageDrawable(new BitmapDrawable(bitmap1));
				Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(),
						R.drawable.p3rfoot);
				btn3.setImageDrawable(new BitmapDrawable(bitmap2));
				layout2.addView(btn1);
				layout2.addView(btn2);
				layout2.addView(btn3);
				btn1.setMinimumHeight(172);
				btn1.setMinimumWidth(172);
				btn2.setMinimumHeight(172);
				btn2.setMinimumWidth(172);
				btn3.setMinimumHeight(172);
				btn3.setMinimumWidth(172);
				bg.addView(layout2);

				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						Bitmap bitmap = BitmapFactory.decodeResource(
								getResources(), R.drawable.u205_normal);
						btn2.setImageDrawable(new BitmapDrawable(bitmap));
						Bitmap bitmap1 = BitmapFactory.decodeResource(
								getResources(), R.drawable.u207_normal);
						btn3.setImageDrawable(new BitmapDrawable(bitmap1));
						new Handler().postDelayed(new Runnable() {

							@Override
							public void run() {
								Bitmap bitmap1 = BitmapFactory.decodeResource(
										getResources(), R.drawable.u192_normal);
								btn1.setImageDrawable(new BitmapDrawable(
										bitmap1));
								new Handler().postDelayed(new Runnable() {

									@Override
									public void run() {
										tv.setText("CALIBRATE DONE");
										tv_long.setText("       Calibration is completed,\nnow put your phone at a safe place\n           within 3 meters from\n            the court boundary");
										bg.addView(ok);
										bg.removeView(layout2);
										InputStream is1 = getResources()
												.openRawResource(
														R.drawable.u246_normal);
										Bitmap bit1 = BitmapFactory
												.decodeStream(is1, null, opt);
										img.setBackgroundDrawable(new BitmapDrawable(
												bit1));
										ok.setText("Ready, GO");
										ok.setOnClickListener(new OnClickListener() {

											@Override
											public void onClick(View arg0) {
												dialog.dismiss();
isfinish = false;
												if (timeThread == null || !timeThread.isAlive()) {
													timeThread = new TimeThread();
													timeThread.start();
												}
												iBWorkoutW1_stop.setVisibility(View.GONE);
												iBWorkoutW1_start
														.setBackgroundResource(R.drawable.button_pause_style);
											
											}
										});
									}
								}, 300);
							}
						}, 1000);
					}

				}, 1000);
			}

		});

	}

	private void createDialog(Dialog dialog) {
		// TODO Auto-generated method stub
		dialog.show();
		Window dialogWindow = dialog.getWindow();
		WindowManager m = getWindowManager();
		Display d = m.getDefaultDisplay();
		WindowManager.LayoutParams p = dialogWindow.getAttributes();
		p.height = (int) (d.getHeight() * 0.765);
		p.width = (int) (d.getWidth() * 0.95);
		dialogWindow.setAttributes(p);
	}
	
}
